<?php
include 'includes/header.php';
require_once '../config/database.php';

$database = new Database();
$db = $database->getConnection();

// Get all brands
$brands_query = "SELECT b.*, COUNT(c.id) as car_count 
                 FROM brands b 
                 LEFT JOIN cars c ON b.id = c.brand_id 
                 GROUP BY b.id 
                 ORDER BY b.name";
$brands = $db->query($brands_query)->fetchAll();

// Get selected brand (default to first brand)
$selected_brand = isset($_GET['brand']) ? $_GET['brand'] : ($brands[0]['id'] ?? null);

// Handle car deletion
if (isset($_POST['delete_car'])) {
    $car_id = $_POST['car_id'];
    
    // Get car images
    $images_query = "SELECT main_image FROM cars WHERE id = ? UNION ALL SELECT image_path FROM car_images WHERE car_id = ?";
    $images_stmt = $db->prepare($images_query);
    $images_stmt->execute([$car_id, $car_id]);
    $images = $images_stmt->fetchAll(PDO::FETCH_COLUMN);

    // Delete physical images
    foreach ($images as $image) {
        if (file_exists('../' . $image)) {
            unlink('../' . $image);
        }
    }

    // Delete car from database
    $delete_query = "DELETE FROM cars WHERE id = ?";
    $delete_stmt = $db->prepare($delete_query);
    
    if ($delete_stmt->execute([$car_id])) {
        set_message('Car deleted successfully');
    } else {
        set_message('Error deleting car', 'danger');
    }
}

// Get cars for selected brand with pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 10;
$offset = ($page - 1) * $per_page;

$where_conditions = [];
$params = [];

if ($selected_brand) {
    $where_conditions[] = "c.brand_id = ?";
    $params[] = $selected_brand;
}

if (!empty($_GET['search'])) {
    $search = '%' . $_GET['search'] . '%';
    $where_conditions[] = "(c.title LIKE ? OR b.name LIKE ? OR m.name LIKE ?)";
    array_push($params, $search, $search, $search);
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get total cars count
$count_query = "SELECT COUNT(*) FROM cars c 
                LEFT JOIN brands b ON c.brand_id = b.id 
                LEFT JOIN models m ON c.model_id = m.id 
                $where_clause";
$count_stmt = $db->prepare($count_query);
$count_stmt->execute($params);
$total_cars = $count_stmt->fetchColumn();
$total_pages = ceil($total_cars / $per_page);

// Get cars
$query = "SELECT c.*, b.name as brand_name, m.name as model_name 
          FROM cars c 
          LEFT JOIN brands b ON c.brand_id = b.id 
          LEFT JOIN models m ON c.model_id = m.id 
          $where_clause 
          ORDER BY c.created_at DESC 
          LIMIT $per_page OFFSET $offset";
$stmt = $db->prepare($query);
$stmt->execute($params);
$cars = $stmt->fetchAll();
?>

<div class="container-fluid py-4">
    <div class="row mb-4">
        <div class="col-md-6">
            <h2>Manage Cars</h2>
        </div>
        <div class="col-md-6 text-end">
            <a href="./manage_brands.php" class="btn btn-primary">
                <i class="fas fa-tags"></i> Brands
            </a>
            <a href="./manage_models.php" class="btn btn-primary">
                <i class="fas fa-car-side"></i> Models
            </a>
            <a href="./add_car.php" class="btn btn-primary">
                <i class="fas fa-plus"></i> Add New Car
            </a>
        </div>
    </div>

    <!-- Search Form -->
    <div class="card shadow mb-4">
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-8">
                    <input type="text" class="form-control" name="search" 
                           placeholder="Search by title, brand, or model..." 
                           value="<?php echo $_GET['search'] ?? ''; ?>">
                </div>
                <div class="col-md-4">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-search"></i> Search
                    </button>
                    <a href="./manage_cars.php" class="btn btn-secondary">
                        <i class="fas fa-redo"></i> Reset
                    </a>
                </div>
            </form>
        </div>
    </div>

    <!-- Brand Tabs -->
    <ul class="nav nav-tabs mb-4">
        <?php foreach ($brands as $index => $brand): ?>
        <li class="nav-item">
            <a class="nav-link <?php echo $brand['id'] == $selected_brand ? 'active' : ''; ?>"
               href="?brand=<?php echo $brand['id']; ?>">
                <?php echo htmlspecialchars($brand['name']); ?>
                <span class="badge bg-secondary ms-2"><?php echo $brand['car_count']; ?></span>
            </a>
        </li>
        <?php endforeach; ?>
    </ul>

    <!-- Cars List -->
    <div class="card">
        <div class="card-body" style="max-height: 70vh; overflow-y: auto;">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead class="sticky-top bg-white">
                        <tr>
                            <th>Image</th>
                            <th>Title</th>
                            <th>Brand/Model</th>
                            <th>Year</th>
                            <th>Price</th>
                            <th>Status</th>
                            <th>Added Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($cars as $car): ?>
                            <tr>
                                <td>
                                    <img src="../<?php echo htmlspecialchars($car['main_image']); ?>" 
                                         alt="<?php echo htmlspecialchars($car['title']); ?>" 
                                         style="width: 80px; height: 60px; object-fit: cover; border-radius: 4px;">
                                </td>
                                <td><?php echo htmlspecialchars($car['title']); ?></td>
                                <td>
                                    <?php echo htmlspecialchars($car['brand_name']); ?> /
                                    <?php echo htmlspecialchars($car['model_name']); ?>
                                </td>
                                <td><?php echo $car['year']; ?></td>
                                <td>$<?php echo number_format($car['price'], 2); ?></td>
                                <td>
                                    <span class="badge bg-<?php 
                                        echo $car['status'] === 'Available' ? 'success' : 
                                            ($car['status'] === 'Reserved' ? 'warning' : 'secondary'); 
                                    ?>">
                                        <?php echo $car['status']; ?>
                                    </span>
                                </td>
                                <td><?php echo date('M d, Y', strtotime($car['created_at'])); ?></td>
                                <td>
                                    <div class="btn-group">
                                        <a href="../car-details.php?id=<?php echo $car['id']; ?>" 
                                           class="btn btn-sm btn-info" target="_blank">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <a href="./edit_car.php?id=<?php echo $car['id']; ?>" 
                                           class="btn btn-sm btn-primary">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <form method="POST" class="d-inline" 
                                              onsubmit="return confirm('Are you sure you want to delete this car?');">
                                            <input type="hidden" name="car_id" value="<?php echo $car['id']; ?>">
                                            <button type="submit" name="delete_car" class="btn btn-sm btn-danger">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
                <nav aria-label="Page navigation" class="mt-4">
                    <ul class="pagination justify-content-center">
                        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                            <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                <a class="page-link" href="?<?php 
                                    echo http_build_query(array_merge($_GET, ['page' => $i])); 
                                ?>"><?php echo $i; ?></a>
                            </li>
                        <?php endfor; ?>
                    </ul>
                </nav>
            <?php endif; ?>
        </div>
    </div>
</div>

<style>
.nav-tabs {
    border-bottom: 2px solid #dee2e6;
    flex-wrap: nowrap;
    -webkit-overflow-scrolling: touch;
}

.nav-tabs .nav-link {
    border: none;
    border-bottom: 2px solid transparent;
    margin-bottom: -2px;
    padding: 0.75rem 1.25rem;
    white-space: nowrap;
    transition: all 0.3s ease;
}

.nav-tabs .nav-link:hover {
    border-color: #e9ecef #e9ecef #dee2e6;
}

.nav-tabs .nav-link.active {
    color: #0d6efd;
    border-color: #0d6efd;
}

.table thead th {
    position: sticky;
    top: 0;
    background: white;
    z-index: 1;
}

.btn-group .btn {
    padding: 0.25rem 0.5rem;
}

.btn-group .btn i {
    width: 14px;
}
</style>

<?php include 'includes/footer.php'; ?> 